//
//  YCAudioPlayer.m
//  YCSchool
//
//  Created by Yanglixia on 16/5/15.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//

#import "YCAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "EMVoiceConverter.h"

@interface YCAudioPlayer() <AVAudioPlayerDelegate> {
    AVAudioPlayer *_player;
    void (^playFinish)(NSError *error);
}

@end

@implementation YCAudioPlayer


+ (instancetype)player
{
    static YCAudioPlayer *shared_player;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared_player = [[self alloc] init];
    });
    return shared_player;
}

// 当前是否正在播放
- (BOOL)isPlaying
{
    return !!_player;
}

// 得到当前播放音频路径
- (NSString *)playingFilePath
{
    NSString *path = nil;
    if (_player && _player.isPlaying)
    {
        path = _player.url.path;
    }
    return path;
}

- (void)asyncPlayWithPath:(NSString *)aFilePath completion:(void(^)(NSError *error))completon
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES
                withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation
                      error:nil];
    
    playFinish = completon;
    NSError *error = nil;
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:aFilePath])
    {
        error = [NSError errorWithDomain:@"文件不存在" code:2 userInfo:nil];
        if (playFinish)
        {
            playFinish(error);
        }
        playFinish = nil;
        
        return;
    }
    
    NSURL *wavUrl = [[NSURL alloc] initFileURLWithPath:aFilePath];
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:wavUrl error:&error];
    if (error || !_player)
    {
        _player = nil;
        error = [NSError errorWithDomain:@"初始化失败"
                                    code:1
                                userInfo:nil];
        if (playFinish)
        {
            playFinish(error);
        }
        playFinish = nil;
        return;
    }
    
    _player.delegate = self;
    [_player prepareToPlay];
    [_player play];
}

// 停止当前播放
- (void)stopCurrentPlaying
{
    if(_player)
    {
        _player.delegate = nil;
        [_player stop];
        _player = nil;
    }
    if (playFinish)
    {
        playFinish = nil;
    }
}

- (void)dealloc
{
    if (_player)
    {
        _player.delegate = nil;
        [_player stop];
        _player = nil;
    }
    playFinish = nil;
}

- (void)asyncPlayAMRFileWithPath:(NSString *)aFilePath completion:(void(^)(NSError *error))completon;
{
    BOOL isNeedSetActive = YES;
    // 如果正在播放音频，停止当前播放。
    if([self isPlaying])
    {
        [self stopCurrentPlaying];
        isNeedSetActive = NO;
    }
    
    if (isNeedSetActive)
    {
        //        // 设置播放时需要的category
        //        [self setupAudioSessionCategory:EM_AUDIOPLAYER
        //                               isActive:YES];
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *wavFilePath = [[aFilePath stringByDeletingPathExtension] stringByAppendingPathExtension:@"wav"];
    
    if (![fileManager fileExistsAtPath:wavFilePath])
    {
        BOOL covertRet = [self convertAMR:aFilePath toWAV:wavFilePath];
        if (!covertRet)
        {
            if (completon)
            {
                completon([NSError errorWithDomain:@""
                                              code:4
                                          userInfo:nil]);
            }
            return ;
        }
    }
    [self asyncPlayWithPath:wavFilePath completion:^(NSError *error)
     {
         //         [self setupAudioSessionCategory:EM_DEFAULT
         //                                isActive:NO];
         if (completon)
         {
             completon(error);
         }
     }];
}

- (BOOL)convertAMR:(NSString *)amrFilePath toWAV:(NSString *)wavFilePath
{
    BOOL ret = NO;
    BOOL isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:amrFilePath];
    if (isFileExists) {
        [EMVoiceConverter amrToWav:amrFilePath wavSavePath:wavFilePath];
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:wavFilePath];
        if (isFileExists) {
            ret = YES;
        }
    }
    
    return ret;
}

#pragma mark - AVAudioPlayer delegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (playFinish) {
        playFinish(nil);
    }
    if (_player) {
        _player.delegate = nil;
        _player = nil;
    }
    playFinish = nil;
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player
                                 error:(NSError *)error{
    if (playFinish)
    {
        NSError *error = [NSError errorWithDomain:@"播放失败"
                                             code:0
                                         userInfo:nil];
        playFinish(error);
    }
    if (_player)
    {
        _player.delegate = nil;
        _player = nil;
    }
}


@end
